{{#error_message}}
    <div class="cm-error cm-{{element_type}}-error">
        {{error_message}}
    </div>
{{/error_message}}

<h2>{{name}}</h2>
<p>{{description}}</p>

{{#all_plans}}
    <!-- plan {{plan_id}} values -->
    <input type="hidden" class="plan_id_per_plan" id="plan_id_{{plan_id}}" value="{{plan_id}}">
    <input type="hidden" class="plan_price_per_plan" id="plan_price_{{plan_id}}" value="{{plan_price}}">
    <input type="hidden" class="plan_minimum_price_per_plan" id="plan_minimum_price_{{plan_id}}" value="{{minimum_price}}">
    <input type="hidden" class="plan_interval_per_plan" id="plan_interval_{{plan_id}}" value="{{plan_interval}}">
    <input type="hidden" class="plan_shipping_per_plan" id="plan_shipping_{{plan_id}}" value="{{shipping}}">
{{/all_plans}}

{{#flexible_price}}<label class="cm-add-amount">Adjust your payment amount:</label><div class="cm-store-flexible-price"><span class="cm-store-currency">{{currency}}</span><input type="number" min="{{minimum_price}}" name="plan_amount" id="plan_flexible_price" value="{{plan_price}}" autocomplete="off" ></div>{{/flexible_price}}<select name="plan_id" id="plan_id" required><option value="">Select a plan</option>{{#all_plans}}<option value="{{plan_id}}">{{plan_name}}</option>{{/all_plans}}</select><a href="#" class="button cm-subscribe" data-price="{{plan_price}}" data-min="{{minimum_price}}" data-plan-id="{{plan_id}}" id="subscribe">$<span class="amount" id="plan_price">{{plan_price}}</span>/<span id="plan_interval">{{plan_interval}}</span> - Subscribe</a>

{{#logged_in}}
    <a href="#" class="cm-my-account cm-secondary-link">My Account</a>
{{/logged_in}}

{{^logged_in}}
    <a href="#" class="cm-login cm-secondary-link">Member's Login</a>
{{/logged_in}}

<div style="clear:both;"></div>

<script type="text/javascript">
    function updatePlanPrice(element, button_element, plan_id) {

        var price = document.querySelector("#plan_price_" + plan_id).value;
        element.innerText = price;
        button_element.dataset.price = price;

        document.querySelector("#plan_flexible_price").value = price;

        return price;
    }

    function updateMinimumPrice(element, plan_id) {
        element.dataset.min = document.querySelector("#plan_minimum_price_" + plan_id).value;

        return document.querySelector("#plan_minimum_price_" + plan_id).value;
    }

    function updatePlanInterval(element, plan_id) {
        element.innerText = document.querySelector("#plan_interval_" + plan_id).value;

        return document.querySelector("#plan_interval_" + plan_id).value;
    }

    function getShippingStatus(plan_id) {
        return document.querySelector("#plan_shipping_" + plan_id).value;
    }

    function getSelectedPlanId(element) {
        if (element) {
            var selected_index = 1;

            if (element.selectedIndex > 0) {
                selected_index = element.selectedIndex;
            } else {
                element.selectedIndex = 1;
            }

            var plan_id = element.options[selected_index].value;
        } else {
            var plan_id = document.getElementsByClassName("plan_id_per_plan")[0].value;
        }

        document.querySelector(".cm-subscribe").setAttribute("data-plan-id", plan_id);

        return plan_id;
    }

    (function() {
    'use strict';
    var cm = window.cashmusic;

    var error_messages = {
        "409": "Whoops, looks like you've already got a subscription with this email and payment method.",
        "412": "There was an error creating your subscription. Contact info@cashmusic.org for help.",
        "404": "The subscription plan you're trying to subscribe to does not appear to exist.",
        "402": "Sorry, the price you entered is less than the minimum subscription price.",
        "417": "Your subscription was created, but we tried to email you a verification and failed. Is this a valid email?",
        "406": "Creation of your subscription failed. Contact info@cashmusic.org for help.",
        "403": "We tried to create a user for you and failed. Contact info@cashmusic.org for help."
    };


    var verification = false;
    var stripe_public_key = false;

    // get stripe public key
    {{#stripe_public_key}}
        var stripe_public_key = "{{stripe_public_key}}";
    {{/stripe_public_key}}

    // is this an email verification run?
    {{#key}}
        var verification = true;
    {{/key}}

    cm.events.add(cm,'ready', function(e) {
        cm.session.start();

        var login = document.querySelector('.cm-login');

        var plan_price = document.getElementById('plan_price');
        var subscribe_button = document.querySelector('.cm-subscribe');
        var flexible_price = document.getElementById('plan_flexible_price');

        var plan_selection = document.querySelector('#plan_id');
        var plan_id = getSelectedPlanId(plan_selection);

        // set shipping true, or to false if there is no shipping
        var shipping = getShippingStatus(plan_id);

        var plan_interval = document.getElementById('plan_interval');

        if (login) {
            cm.events.add(login, 'click', function (e) {
                e.preventDefault();
                cm.overlay.reveal({"element":"{{element_id}}","endpoint":"{{public_url}}","state":"login"});
            });
        }

        updatePlanPrice(plan_price, subscribe_button, plan_id);
        updateMinimumPrice(subscribe_button, plan_id);
        updatePlanInterval(plan_interval, plan_id);


        if (plan_selection) {
            cm.events.add(plan_selection, 'change', function (e) {
                var plan_id = getSelectedPlanId(plan_selection);

                updatePlanPrice(plan_price, subscribe_button, plan_id);
                updateMinimumPrice(subscribe_button, plan_id);
                updatePlanInterval(plan_interval, plan_id);

                shipping = getShippingStatus(plan_id);

            });

        }


        if (verification !== false) {
            cm.overlay.reveal({"element":"{{element_id}}","endpoint":"{{public_url}}","state":"verified"});
        }

        var account = document.querySelector('.cm-my-account');

        if (account) {
            cm.events.add(account, 'click', function (e) {
                e.preventDefault();
                cm.overlay.reveal({"element":"{{element_id}}","endpoint":"{{public_url}}","state":"logged_in_index"});
            });
        }

        if (flexible_price) {
            cm.events.add(flexible_price,'keyup', function() {
                var price = (flexible_price.value != "") ? flexible_price.value : "{{plan_price}}";
                plan_price.innerHTML = price;
                subscribe_button.setAttribute("data-price", price);
            });
        }

        if (subscribe_button) {
            // user triggered the subscribe button
            cm.events.add(subscribe_button, 'click', function (e) {
                e.preventDefault();
                var price = subscribe_button.getAttribute("data-price");
                var minimum = subscribe_button.getAttribute('data-min');

                if (parseInt(price) < parseInt(minimum)) {
                    flexible_price.value = minimum;
                    plan_price.innerHTML = minimum;
                    subscribe_button.setAttribute("data-price", minimum);
                    //flexible_price.className += "shake";
                    return false;
                } else {
                    /*flexible_price.className =
                            flexible_price.className.replace(new RegExp('(?:^|\\s)'+ 'shake' + '(?:\\s|$)'), ' ');*/
                }

                var plan_id = subscribe_button.getAttribute("data-plan-id");

                 cm.checkout.begin({
                     "stripe": stripe_public_key,
                     "paypal": false,
                     "currency": "usd", // USD = auto default
                     "recurring": true,
                     "shipping": shipping,
                     "total": "{{currency}}" + parseFloat(price),
                     "transaction_message": "/"+document.querySelector("#plan_interval").innerText
                 });
            });

            cm.events.add(cm, 'checkoutdata', function (payment) {
                var f = document.createElement('form');
                f.method = 'post';
                f.action = '';
                f.id = "subscription_form";

                var els = ['cash_request_type','cash_action','element_id','price','stripe','origin','email_address','subscription_plan','customer_name','geo', 'shipping_info', 'finalize_url'];
                for (var i = 0, len = els.length; i < len; i++) {
                    var inp = document.createElement('input');
                    inp.type = 'hidden';
                    inp.name = els[i];
                    inp.value = '';
                    f.appendChild(inp);
                }

                f.cash_request_type.value = 'commerce';
                f.cash_action.value = 'initiatesubscription';
                {{#session_id}}f.session_id = '{{session_id}}';{{/session_id}}
                f.element_id.value = {{element_id}};
                f.price.value = parseFloat(subscribe_button.getAttribute('data-price'));
                f.subscription_plan.value = subscribe_button.getAttribute('data-plan-id');
                f.origin.value = payment.detail.origin;
                f.email_address.value = payment.detail.email;
                f.customer_name.value = payment.detail.name;
                f.geo.value = cm.geo;

                if (cm.embedded) {
                    if (cm.get['params']['location']) {
                        f.finalize_url.value = encodeURI(cm.get['params']['location']);
                    } else {
                        f.finalize_url.value = encodeURI(window.location.href);
                    }
                } else {
                    f.finalize_url.value = encodeURI(top.location.href);
                }

                if (payment.detail.stripe) {
                    f.stripe.value = payment.detail.stripe;
                }

                // add shipping to form
                if (payment.detail.shipping) {
                    f.shipping_info.value = JSON.stringify(payment.detail.shipping);

                }

                initiatePayment(f);
                //var f = undefined;

            });

            cm.loadScript(cm.path + '/checkout/checkout.js', function () {
               cm.checkout.prep();
            });
        }

        function initiatePayment(f) {
            cm.ajax.send(
                 '{{public_url}}/request/payload',
                 cm.ajax.encodeForm(f),
                 function(details) {
                     console.log("inside the ajax call response");
                     if (details.substring(0,4) == 'http') {
                         top.location.href = details;
                     } else if (details == '200') {
                         cm.overlay.reveal({"element":"{{element_id}}","endpoint":"{{public_url}}","state":"success"});
                         return true;
                     } else {
                         cm.overlay.reveal(error_messages[details]);
                     }
                 },
                 function(details) {
                     cm.overlay.reveal(error_messages[details]);
                 }
            );
        }
        //
    });

}());
</script>
